package com.homedo.odin.solution.service.bizservice.pc;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.homedo.core.common.base.dto.Meta;
import com.homedo.core.common.exception.BizException;
import com.homedo.core.common.util.BeanUtils;
import com.homedo.core.common.util.CommonDataUtil;
import com.homedo.core.common.util.NumberHelper;
import com.homedo.odin.solution.contract.pc.AddSolDownloadReq;
import com.homedo.odin.solution.contract.pc.DlAndCollectSolutionResp;
import com.homedo.odin.solution.contract.personal.userhomepage.AddPopularityReq;
import com.homedo.odin.solution.contract.wap.SolutionDownloadsResp;
import com.homedo.odin.solution.enumcode.TemplateCodeEnum;
import com.homedo.odin.solution.enumcode.basic.CommonTypeDataEnum;
import com.homedo.odin.solution.enumcode.basic.DownloadCollectEnum;
import com.homedo.odin.solution.enumcode.basic.ErrorCodeEnum;
import com.homedo.odin.solution.enumcode.other.PopularityEnum;
import com.homedo.odin.solution.model.dto.DlAndCollectSolutionRespBean;
import com.homedo.odin.solution.model.dto.SolutionDownloadResponseBean;
import com.homedo.odin.solution.model.dto.UserSolutionResult;
import com.homedo.odin.solution.model.entity.Solution;
import com.homedo.odin.solution.model.entity.UserSolution;
import com.homedo.odin.solution.service.CommonTypeDataServiceImpl;
import com.homedo.odin.solution.service.SolutionServiceImpl;
import com.homedo.odin.solution.service.UserSolutionServiceImpl;
import com.homedo.odin.solution.service.bizservice.personal.CommonBizService;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author: zhaoxudong
 * @date: 2018/4/8 15:25
 * @Description:
 */
@Service
public class DownloadsBizService {

    @Autowired
    UserSolutionServiceImpl userSolutionService;
    @Autowired
    SolutionServiceImpl solutionService;
    @Autowired
    CommonBizService commonBizService;
    @Autowired
    CommonTypeDataServiceImpl commonTypeDataService;

    public SolutionDownloadsResp solutions(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        PageInfo<SolutionDownloadResponseBean> pageInfo = new PageInfo<>(
                userSolutionService.solutions(DownloadCollectEnum.DOWNLOAD.getDbValue()));
        return BeanUtils.transfrom(SolutionDownloadsResp.class, pageInfo);
    }

    /**
     * 新增下载方案记录
     */
    public void addSolutions(AddSolDownloadReq req) {
        Long solutionId = req.getSolutionId();
        Integer userId = req.getUserId();
        if (!NumberHelper.validatePositive(solutionId)) {
            throw new BizException(Meta.CODE_451.getCode(), "solutionId不合规");
        }
        if (!NumberHelper.validatePositive(req.getUserId())) {
            throw new BizException(Meta.CODE_451.getCode(), "uid不合规");
        }
        Solution solution = solutionService.findBySolutionId(solutionId);
        if (solution == null) {
            throw new BizException(ErrorCodeEnum.NotExist.getDbValue(), "该方案不存在");
        }
        UserSolution userSolution = userSolutionService
                .getUserSolution(userId, solutionId, DownloadCollectEnum.DOWNLOAD.getDbValue());
        //userSolution表中存在记录,则只新增下载量,否则还需插入下载记录
        if (userSolution == null) {
            //插入下载记录
            UserSolution uSolution = new UserSolution();
            uSolution.setCreateTime(new Date());
            uSolution.setUserId(userId);
            uSolution.setSolutionId(solutionId);
            uSolution.setActionType(DownloadCollectEnum.DOWNLOAD.getDbValue());
            userSolutionService.addUserSolution(uSolution);

            if (solution.getIsFree() < 1) {
                //发送通知
                Map<String, String> paramMap = com.google.common.collect.Maps.newHashMap();
                paramMap.put("@@userName", solution.getUserName());
                paramMap.put("@@bizId", solution.getSolutionId().toString());
                paramMap.put("@@solution", solution.getSolutionName());
                paramMap.put("@@money", "0");
                commonBizService.sentMessage(paramMap, solution.getUserId(), 0, TemplateCodeEnum.solution_down.name());
            }
            //增加人气值
            AddPopularityReq req1 = new AddPopularityReq();
            req1.setOperationId(userId);
            req1.setTargetId(solution.getUserId());
            req1.setType(PopularityEnum.Download.getType());
            //增加人气
            commonBizService.addPopularity(req1);
        }
        //新增下载量
        solutionService.addSolutionDownload(solutionId);
    }

    public DlAndCollectSolutionResp userDownloadSol(Integer userId, String solutionName, Integer solutionStatus,
            Long startDate, Long endDate, Integer pageNum, Integer pageSize) {
        if (!NumberHelper.validatePositive(userId)) {
            throw new BizException(Meta.CODE_451.getCode(), "用户id不合法!");
        }
        if (startDate != null && endDate != null && startDate > endDate) {
            throw new BizException(Meta.CODE_451.getCode(), "时间区间不合法!");
        }
        Date createStartTime = null;
        Date createEndTime = null;
        if (startDate != null) {
            createStartTime = new Date(startDate);
        }
        if (endDate != null) {
            createEndTime = new Date(endDate);
        }
        PageInfo<UserSolutionResult> queryResult = new PageInfo<>(userSolutionService.querySdownloadList
                (userId, DownloadCollectEnum.DOWNLOAD.getDbValue(), solutionName, solutionStatus, createStartTime,
                        createEndTime));

        List<UserSolutionResult> resultList = queryResult.getList();
        List<DlAndCollectSolutionRespBean> responseList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(resultList)) {
            HashMap<String, String> yjxtsxMap = commonTypeDataService
                    .getDataById(CommonTypeDataEnum.YJXTSX.getDbValue());
            DlAndCollectSolutionRespBean result;
            for (UserSolutionResult userSolutionResult : resultList) {
                result = BeanUtils.transfrom(DlAndCollectSolutionRespBean.class, userSolutionResult);
                result.setSolutionStatus(userSolutionResult.getStatus());
                result.setFirstSysAttr(
                        CommonDataUtil.mappedField(String.valueOf(userSolutionResult.getFirstSysAttr()), yjxtsxMap));
                responseList.add(result);
            }
        }
        DlAndCollectSolutionResp resp = BeanUtils.transfrom(DlAndCollectSolutionResp.class, queryResult);
        resp.setList(responseList);
        return resp;
    }
}
